package com.moody.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/*
 * Copyright © Moody analytics
 *
 * @Author: Wang Fuqiang
 * @Time: 2011-11-28 下午01:58:21
 * @Modified by: 
 * @Description: 模型管理
 */

import com.moody.hibernate.domain.CodeLib;
import com.moody.hibernate.domain.CustInfo;
import com.moody.hibernate.domain.MainscaleHis;
import com.moody.hibernate.domain.MainscaleInfo;
import com.moody.hibernate.domain.ModelHis;
import com.moody.hibernate.domain.ModelInfo;
import com.moody.hibernate.domain.ModelLevel;
import com.moody.init.DataDictionary;
import com.moody.init.ParamModelInit;
import com.moody.init.ReportItemInit;
import com.moody.init.ReportModelInit;
import com.moody.service.CustomerService;
import com.moody.service.ModelService;
import com.moody.service.ObligationService;
import com.moody.util.CalendarUtil;

/*
 * Copyright © Moody analytics   
 *
 * @Title: ModelController.java 
 * @Package： com.moody.web 
 * @author： Fuqiang Wang
 * @Description: 模型管理：核心功能
 * @date： 2012-3-16 上午11:42:32
 * @Modified by: Fuqiang Wang 
 * @version V1.0   
 */


@Controller
@RequestMapping("/model")
public class ModelController {
	private static final Logger log = LoggerFactory.getLogger(ModelController.class);
	
	@Resource
	private ModelService modelService;
	
	//列出所有的模型版本信息，按照状态和时间排序
	@RequestMapping("/listSortedModel")
	public void listSortedModel(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		List<ModelHis> modelList = new ArrayList<ModelHis>();
		
		// 对模型历史进行排序
		
		List<ModelHis> notReleasedModelList = modelService.findNotReleasedModelHis();
		List<ModelHis> nonNotReleasedModelList = modelService.findNonNotReleasedModelHis();
		
		modelList.addAll(notReleasedModelList);
		modelList.addAll(nonNotReleasedModelList);
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		
		List<ModelHis> pageList;
		if(modelList.size()>start+limit)
			pageList = modelList.subList(start, limit+start); 
		else
			pageList = modelList.subList(start,modelList.size());
		
		for(ModelHis model : pageList){
			model.setModelState(DataDictionary.getInstance().getNameByCodeAndId("ModelState", model.getModelState()));
			log.info("modelKind2: "+model.getModelKind2());
			if(model.getModelKind2() != null)	
				model.setModelKind2(this.getModelKind2(model.getModelKind2()));
			
			model.setModelKind1(DataDictionary.getInstance().getNameByCodeAndId("CustType", model.getModelKind1()));
		}
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", modelList.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		log.info("JSON数据："+myCustJO);
		
	}
	
	//通过ID获得打分卡小类名称
	private String getModelKind2(String modelKind2) {
		String result = "";
		if(modelKind2.startsWith("01")){
			result = DataDictionary.getInstance().getNameByCodeAndId("EnterType", modelKind2);
		}else if(modelKind2.startsWith("02")){
			result = DataDictionary.getInstance().getNameByCodeAndId("PubType", modelKind2);
		}else if(modelKind2.startsWith("03")){
			result = DataDictionary.getInstance().getNameByCodeAndId("FinanType", modelKind2);
		}else if(modelKind2.startsWith("04")){
			result = DataDictionary.getInstance().getNameByCodeAndId("IndType", modelKind2);
		}
		
		return result;
	}

	//版本生效
	@RequestMapping("/effectModel")
	public void effectModel(HttpServletRequest request,
			HttpServletResponse response){
		
		String modelId = request.getParameter("modelId");
		String updateLog = request.getParameter("updateLog");
		ModelHis model = new ModelHis();
		
		if(modelId!=null && !modelId.equals("")){
			
			model = modelService.findModelHisById(modelId);
			
			//置其他已生效Model为失效状态
			ModelHis effectedModel = new ModelHis();
			effectedModel = modelService.findModelByKind1AndKind2AndState(model.getModelKind1(), model.getModelKind2(), ModelHis.EFFECTED);
			if (effectedModel != null){
				effectedModel.setModelState(ModelHis.NOT_EFFECTED);
				effectedModel.setEndDate(CalendarUtil.getCurrentDateStr());
				effectedModel.setUpdateDate(CalendarUtil.getCurrentDateStr());
				effectedModel.setStartDate("");
				modelService.updateModelHis(effectedModel);
			}
			
			//更新当前Model为生效状态
			model.setModelState(ModelHis.EFFECTED);
			model.setUpdateLog(updateLog);
			model.setStartDate(CalendarUtil.getCurrentDateStr());
			model.setEndDate("");
			model.setUpdateDate(CalendarUtil.getCurrentDateStr());
			modelService.updateModelHis(model);
			
			//ToDo--记录审批意见--ToDo

		}
	}
	
	//版本发布
	@RequestMapping("/releaseModel")
	public void releaseModel(HttpServletRequest request,
			HttpServletResponse response){
		
		String modelId = request.getParameter("modelId");
		String updateLog = request.getParameter("updateLog");
		ModelHis model = new ModelHis();
		
		if(modelId!=null && !modelId.equals("")){
			
			model = modelService.findModelHisById(modelId);	
			model.setUpdateLog(updateLog);
			model.setModelState(ModelHis.RELEASED);
			model.setUpdateDate(CalendarUtil.getCurrentDateStr());
			modelService.updateModelHis(model);

		}
	}

	//删除未发布版本

	@RequestMapping("/deleteModel")
	public String deleteModel(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String modelId = request.getParameter("modelId");
		if(modelId!=null && !modelId.equals("")){
			modelService.deleteModel(modelId);
		}
		
		return "model/VersionManagement";
		
	}

	//删除发布版本，其实是做更新操作
	@RequestMapping("/deleteReleasedModel")
	public void deleteReleasedModel(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String modelId = request.getParameter("modelId");
		String updateLog = request.getParameter("updateLog");
		ModelHis model = null;
		if(modelId!=null && !modelId.equals("")){
			model = modelService.findModelHisById(modelId);
		}
		
		if(model==null){
			log.info("id为:　"+modelId+"的版本不存在");
		}else{
			model.setDeleteFlag(ModelHis.DELETED);
			model.setUpdateLog(updateLog);
			model.setUpdateDate(CalendarUtil.getCurrentDateStr());
			
			modelService.updateModelHis(model);
		}
		
	}
	
	//将发布置为未发布
	@RequestMapping("/notReleaseModel")
	public void notReleaseModel(HttpServletRequest request,
			HttpServletResponse response){
		
		String modelId = request.getParameter("modelId");
		String updateLog = request.getParameter("updateLog");
		ModelHis model = null;
		if(modelId!=null && !modelId.equals("")){
			model = modelService.findModelHisById(modelId);
		}
		
		if(model==null){
			log.info("id为:　"+modelId+"的版本不存在");
		}else{
			model.setUpdateLog(updateLog);
			model.setUpdateDate(CalendarUtil.getCurrentDateStr());
			model.setModelState(ModelHis.NOT_RELEASED);
			
			modelService.updateModelHis(model);
		}

	}
	
	//检查该版本是否存在
	@RequestMapping("/checkModel")
	public void checkCustomer(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String version = request.getParameter("modelVersion");
		String kind1 = request.getParameter("modelKind1");
		String kind2 = request.getParameter("modelKind2");
		int isExit = 0;
		
		if (modelService.findModelByKind1AndKind2AndVersion(kind1, kind2, version)){
			isExit = 1;
			response.getWriter().print(isExit);
		}
		else{
			isExit = 0;
			response.getWriter().print(isExit);
		}
		
	}
	
	@RequestMapping("/addModel")
	public String addModel(HttpServletRequest request,
			HttpServletResponse response, ModelHis model) throws IOException {
		
		model.setUpdateDate(CalendarUtil.getCurrentDateStr());
		model.setModelState(ModelHis.NOT_RELEASED);
		model.setDeleteFlag(ModelHis.NOTDELETED);
		modelService.insertModel(model);
		
		String modelKind1 = DataDictionary.getInstance().getNameByCodeAndId("CustType", model.getModelKind1());
		String modelKind2 = this.getModelKind2(model.getModelKind2());
		if(model.getModelKind1().equals("04")){
			model.setModelName("【申请评分卡】_"+modelKind1+"_"+modelKind2+"_"+model.getModelVersion());
		}
		else model.setModelName("【信用评分卡】_"+modelKind1+"_"+modelKind2+"_"+model.getModelVersion());
		modelService.updateModelHis(model);
		
		request.getSession().removeAttribute("modelId");
		request.getSession().setAttribute("modelId", model.getModelId());
		request.getSession().removeAttribute("model");
		request.getSession().setAttribute("model", model);
		
		if(model.getModelKind1().equals("04")){
				return "model/VersionManagement_IndModel";
			}
		else
			return "model/VersionManagement_AddModel";
	}
	
	//列出某个版本所有的定量因素,定性因素，调整项，按照记录标记查询db并构造数据结构
	@RequestMapping("/listModelItems")
	public void listModelItems(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
	
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
	 
		List<ModelInfo> itemList = new ArrayList<ModelInfo>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		String dataFlag = request.getParameter("dataFlag");
		 
		itemList =modelService.findModelInfoByModelIdAndDataFlag(modelId,dataFlag); 
		
		//定量因素
//		if(dataFlag.equals("1")){
//			
//		}

//		//构造定量因素数据结构
//		if(dataFlag.equals(ModelInfo.QUANTITY_FACTOR)){
//			//利用两层map，第一层存大类，第二层存该大类下的因素，用map来存储此结构
//			Map<String,Map<String,ModelInfo>> map = new HashMap<String,Map<String,ModelInfo>>();
//			for(ModelInfo modelInfo : itemList){
//				//map中存在该大类，将因素加入此大类中
//				if(map.containsKey(modelInfo.getDescribe1())){
//					map.get(modelInfo.getDescribe1()).put(modelInfo.getItemNo(), modelInfo);
//				}else{
//					Map<String,ModelInfo> subMap = new HashMap<String,ModelInfo>();
//					subMap.put(modelInfo.getItemNo(), modelInfo);
//					map.put(modelInfo.getDescribe1(), subMap);
//				}
//			}
//		}
//		//构造定性因素数据结构
//		else if(dataFlag.equals(ModelInfo.QUALITY_FACTOR)){
//			Map<String,Map<String,Map<String,ModelInfo>>> map = new HashMap<String,Map<String,Map<String,ModelInfo>>>();
//			
//		}else if(dataFlag.equals(ModelInfo.ADJUST_ITEM)){
//			
//			
//		}else{
//			log.info("不存在该dataFlag。(1.定量 2.定性 3调整项)");
//		}
		
		//如果是定量因素，显示子类因素名，而非FR001之类的code, 对于小水电，金融和房地产，则直接显示。
		if(("1").equals(dataFlag)){
			for(ModelInfo modelInfo : itemList){
				String describe2 = ReportItemInit.getInstance().getReportItem().get(modelInfo.getDescribe2());
				
				if(describe2!=null && !("").equals(describe2))
					modelInfo.setDescribe2(ReportItemInit.getInstance().getReportItem().get(modelInfo.getDescribe2()));
			}
		}
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", itemList.size());
		myCustMap.put("resultData", itemList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
	}	
	
	@RequestMapping("/viewDetail")
	public String viewDetail(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		request.getSession().removeAttribute("modelId");
		request.getSession().setAttribute("modelId", request.getParameter("modelId"));
		request.getSession().removeAttribute("model");
		ModelHis model = modelService.findModelHisById(request.getParameter("modelId"));
		request.getSession().setAttribute("model", modelService.findModelHisById(request.getParameter("modelId")));
		request.setAttribute("returnFlag", request.getParameter("returnFlag"));	
		request.getSession().removeAttribute("modelKind2");
		if(model.getModelKind2() != null)	
		request.getSession().setAttribute("modelKind2", this.getModelKind2(model.getModelKind2()));
		
		String kind2 = model.getModelKind2();
		if(model.getModelKind1().equals("04"))
			return "model/VersionManagement_IndModel";
		else if(kind2.equals("0103") || kind2.equals("0105") || kind2.equals("0302")){ //定量数据需手工输入
			return "model/VersionManagement_AddModel_Special";
		}
		else
			return "model/VersionManagement_AddModel";
	}
	
	//添加定性因素
	@RequestMapping("/addQua")
	public void addQua(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		List<ModelInfo> list = new ArrayList<ModelInfo>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		
		String describe1 = request.getParameter("describe1");
		String describe2 = request.getParameter("describe2");
		String describe3 = request.getParameter("describe3");
		
		String itemDescribe1 = request.getParameter("itemDescribe1");
		String itemDescribe2 = request.getParameter("itemDescribe2");
		String itemDescribe3 = request.getParameter("itemDescribe3");
		String itemDescribe4 = request.getParameter("itemDescribe4");
		String itemDescribe5 = request.getParameter("itemDescribe5");
		String itemDescribe6 = request.getParameter("itemDescribe6");
		
		String itemValue1 = request.getParameter("itemValue1");
		String itemValue2 = request.getParameter("itemValue2");
		String itemValue3 = request.getParameter("itemValue3");
		String itemValue4 = request.getParameter("itemValue4");
		String itemValue5 = request.getParameter("itemValue5");
		String itemValue6 = request.getParameter("itemValue6");
		
		String itemWeight = request.getParameter("itemWeight");
		
		DecimalFormat df = new DecimalFormat("0");
		String itemNo =String.valueOf(df.format((System.currentTimeMillis() + Math.floor((Math.random() * 10000)))));
		
		if(itemDescribe1!=null &&!itemDescribe1.equals("") && itemValue1!=null && !itemValue1.equals("") ){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUALITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe1);
			modelInfo.setItemValue(Double.valueOf(itemValue1));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe2!=null &&!itemDescribe2.equals("") && itemValue2!=null && !itemValue2.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUALITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe2);
			modelInfo.setItemValue(Double.valueOf(itemValue2));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe3!=null &&!itemDescribe3.equals("")&& itemValue3!=null && !itemValue3.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUALITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe3);
			modelInfo.setItemValue(Double.valueOf(itemValue3));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe4!=null &&!itemDescribe4.equals("")&& itemValue4!=null && !itemValue4.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUALITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe4);
			modelInfo.setItemValue(Double.valueOf(itemValue4));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe5!=null &&!itemDescribe5.equals("")&& itemValue5!=null && !itemValue5.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUALITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe5);
			modelInfo.setItemValue(Double.valueOf(itemValue5));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe6!=null &&!itemDescribe6.equals("")&& itemValue6!=null && !itemValue6.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUALITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe6);
			modelInfo.setItemValue(Double.valueOf(itemValue6));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
			
		//批量插入
		modelService.insertModelInfo(list);
		
		response.getWriter().print("{success:true}");

		
	}
	
	//修改定性因素
	@RequestMapping("/editQua")
	public void editQua(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String serialNo = request.getParameter("serialNo");
		String field = request.getParameter("field");
		String originalValue = request.getParameter("originalValue");
		String modifiedValue = request.getParameter("modifiedValue");
		String describe2 = request.getParameter("describe2");
		
		List<ModelInfo> itemList = new ArrayList<ModelInfo>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		String dataFlag = request.getParameter("dataFlag");
		 
		if(field.equals("describe2")) describe2 = originalValue;
		itemList =modelService.findModelInfoByModelIdAndDescribe2AndDataFlagAndModifiedField(modelId,describe2,dataFlag,field,originalValue); 
		
		for (ModelInfo mi: itemList){
			if(field.equals("describe1")){
				mi.setDescribe1(modifiedValue);
			}
			else if (field.equals("describe2")){
				mi.setDescribe2(modifiedValue);
			}
			else if (field.equals("describe3")){
				mi.setDescribe3(modifiedValue);
			}
			else if (field.equals("itemDescribe")){
				mi.setItemDescribe(modifiedValue);
			}
			else if (field.equals("itemValue")){
				mi.setItemValue(Double.valueOf(modifiedValue));	
			}
			else if (field.equals("itemWeight")){
				mi.setItemWeight(Double.valueOf(modifiedValue));
			}
			modelService.updateModelInfo(mi);
		}
		
		response.getWriter().print("{success:true}");
		
	}
	


	@RequestMapping("/addRatio")
	public void addRatio(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		List<ModelInfo> list = new ArrayList<ModelInfo>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		
		String describe1 = request.getParameter("describe1");
		String describe2 = request.getParameter("describe2");
		String describe3 = request.getParameter("describe3");
		
		String itemDescribe1 = request.getParameter("itemDescribe1");
		String itemDescribe2 = request.getParameter("itemDescribe2");
		String itemDescribe3 = request.getParameter("itemDescribe3");
		String itemDescribe4 = request.getParameter("itemDescribe4");
		String itemDescribe5 = request.getParameter("itemDescribe5");
		String itemDescribe6 = request.getParameter("itemDescribe6");
		String itemDescribe7 = request.getParameter("itemDescribe7");
		String itemDescribe8 = request.getParameter("itemDescribe8");
		String itemDescribe9 = request.getParameter("itemDescribe9");
		String itemDescribe10 = request.getParameter("itemDescribe10");
		
		String itemValue1 = request.getParameter("itemValue1");
		String itemValue2 = request.getParameter("itemValue2");
		String itemValue3 = request.getParameter("itemValue3");
		String itemValue4 = request.getParameter("itemValue4");
		String itemValue5 = request.getParameter("itemValue5");
		String itemValue6 = request.getParameter("itemValue6");
		
		String itemWeight = request.getParameter("itemWeight");
		
		DecimalFormat df = new DecimalFormat("0");
		String itemNo =String.valueOf(df.format((System.currentTimeMillis() + Math.floor((Math.random() * 10000)))));
		//判断是否为特殊的定量数据（子因素为手工输入）,若是，则用另一种方式设置itemNo
		ModelHis mh = modelService.findModelHisById(modelId);
		String kind2 = mh.getModelKind2();
		boolean isSpecial = false;
		if(kind2.equals("0103") || kind2.equals("0105") || kind2.equals("0302")) isSpecial = true;
		
		if(itemDescribe1!=null &&!itemDescribe1.equals("") && itemDescribe2!=null 
				&&!itemDescribe2.equals("")&& itemValue1!=null && !itemValue1.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUANTITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe("("+itemDescribe1+","+itemDescribe2+")");
			modelInfo.setItemValue(Double.valueOf(itemValue1));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			if(isSpecial) modelInfo.setItemNo(itemNo);
			else modelInfo.setItemNo(describe2);
			list.add(modelInfo);
		}
		
		if(itemDescribe3!=null &&!itemDescribe3.equals("") && itemDescribe4!=null 
				&&!itemDescribe4.equals("")&& itemValue2!=null&& !itemValue2.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUANTITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe("("+itemDescribe3+","+itemDescribe4+")");
			modelInfo.setItemValue(Double.valueOf(itemValue2));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			if(isSpecial) modelInfo.setItemNo(itemNo);
			else modelInfo.setItemNo(describe2);
			list.add(modelInfo);
		}
		
		if(itemDescribe5!=null &&!itemDescribe5.equals("") && itemDescribe6!=null 
				&&!itemDescribe6.equals("")&& itemValue3!=null && !itemValue3.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUANTITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe("("+itemDescribe5+","+itemDescribe6+")");
			modelInfo.setItemValue(Double.valueOf(itemValue3));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			if(isSpecial) modelInfo.setItemNo(itemNo);
			else modelInfo.setItemNo(describe2);
			list.add(modelInfo);
		}
		
		if(itemDescribe7!=null &&!itemDescribe7.equals("") && itemDescribe8!=null 
				&&!itemDescribe8.equals("")&& itemValue4!=null && !itemValue4.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUANTITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe("("+itemDescribe7+","+itemDescribe8+")");
			modelInfo.setItemValue(Double.valueOf(itemValue4));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			if(isSpecial) modelInfo.setItemNo(itemNo);
			else modelInfo.setItemNo(describe2);
			list.add(modelInfo);
		}
		
		if(itemDescribe9!=null &&!itemDescribe9.equals("") && itemDescribe10!=null 
				&&!itemDescribe10.equals("") && itemValue5!=null && !itemValue5.equals("")){
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.QUANTITY_FACTOR);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe("("+itemDescribe9+","+itemDescribe10+")");
			modelInfo.setItemValue(Double.valueOf(itemValue5));
			modelInfo.setItemWeight(Double.valueOf(itemWeight));
			if(isSpecial) modelInfo.setItemNo(itemNo);
			else modelInfo.setItemNo(describe2);
			list.add(modelInfo);
		}
		
		//批量插入
		modelService.insertModelInfo(list);
		
		response.getWriter().print("{success:true}");
		
	}
	
	
	//修改定量因素
	@RequestMapping("/editRatio")
	public void editRatio(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String serialNo = request.getParameter("serialNo");
		String field = request.getParameter("field");
		String originalValue = request.getParameter("originalValue");
		String modifiedValue = request.getParameter("modifiedValue");
		String describe2 = request.getParameter("describe2");
		
		List<ModelInfo> itemList = new ArrayList<ModelInfo>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		String dataFlag = request.getParameter("dataFlag");
		 
		if(field.equals("describe2")) describe2 = originalValue;
		List<Map<String,String>> resultList = ReportModelInit.getInstance().getEnterFinancialIndexItemFromModel();
		for(Map<String,String> item :resultList){
			if(item.get("name").equals(describe2)){
				describe2 = item.get("code");
				break;
			}
		}
		if(field.equals("describe2"))originalValue = describe2;
		itemList =modelService.findModelInfoByModelIdAndDescribe2AndDataFlagAndModifiedField(modelId,describe2,dataFlag,field,originalValue);
		
		List<ModelInfo> list = modelService.findModelInfoByModelIdAndDescribe2AndDataFlag(modelId, describe2, dataFlag, field);
		
		for (ModelInfo mi: itemList){
			if(field.equals("describe1")){
				mi.setDescribe1(modifiedValue);
			}
			else if (field.equals("describe2")){
				for(Map<String,String> item :resultList){
					if(item.get("name").equals(modifiedValue)){
						modifiedValue = item.get("code");
						mi.setDescribe2(modifiedValue);
						break;
					}
				}
			}
			else if (field.equals("describe3")){
				mi.setDescribe3(modifiedValue);
			}
			else if (field.equals("itemDescribe")){
				mi.setItemDescribe(modifiedValue);
				//同时将同子类下的含有该数值的区间修改
				String[] orginArray = new String[2];
				String[] modifiedArray = new String[2];
				StringTokenizer st1 = new StringTokenizer(originalValue,"(),");
				StringTokenizer st2 = new StringTokenizer(modifiedValue,"(),");
				int i=0, j=0;
				while(st1.hasMoreTokens()){
					String s = st1.nextToken();
					log.info(s);
					orginArray[i] = s.trim();
					i++;
				}
				
				while(st2.hasMoreTokens()){
					String s = st2.nextToken();
					log.info(s);
					modifiedArray[j] = s.trim();
					j++;
				}
				
				//找出修改后的数值，以及修改前的数值
				String orgin = "";
				String modified = "";
				if(orginArray[0].equals(modifiedArray[0])){
					orgin = orginArray[1];
					modified = modifiedArray[1];
				}else if(orginArray[1].equals(modifiedArray[1])){
					orgin = orginArray[0];
					modified = modifiedArray[0];
				}
		
				for(ModelInfo  modelInfo : list){
					if(modelInfo.getItemDescribe().contains(orgin)){
						modelInfo.setItemDescribe(modelInfo.getItemDescribe().replace(orgin, modified));
						modelService.updateModelInfo(modelInfo);
					}
				}
				
			}
			else if (field.equals("itemValue")){
				mi.setItemValue(Double.valueOf(modifiedValue));	
			}
			else if (field.equals("itemWeight")){
				mi.setItemWeight(Double.valueOf(modifiedValue));
			}
			modelService.updateModelInfo(mi);
		}
		
		response.getWriter().print("{success:true}");
		
	}
	
	@RequestMapping("/addAdjustment")
		public void addAdjustment(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		List<ModelInfo> list = new ArrayList<ModelInfo>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		
		String describe1 = request.getParameter("describe1");
		String describe2 = request.getParameter("describe2");
		String describe3 = request.getParameter("describe3");
		if(describe3.equals("")) describe3 = describe1; //为了显示需要，否则若describe3为空时，显示存在问题
		if(describe2 == null) describe2 = "";
		
		String itemDescribe1 = request.getParameter("itemDescribe1");
		String itemDescribe2 = request.getParameter("itemDescribe2");
		String itemDescribe3 = request.getParameter("itemDescribe3");
		String itemDescribe4 = request.getParameter("itemDescribe4");
		String itemDescribe5 = request.getParameter("itemDescribe5");
		String itemDescribe6 = request.getParameter("itemDescribe6");
		String itemDescribe7 = request.getParameter("itemDescribe7");
		
		String itemValue1 = request.getParameter("itemValue1");
		String itemValue2 = request.getParameter("itemValue2");
		String itemValue3 = request.getParameter("itemValue3");
		String itemValue4 = request.getParameter("itemValue4");
		String itemValue5 = request.getParameter("itemValue5");
		String itemValue6 = request.getParameter("itemValue6");
		String itemValue7 = request.getParameter("itemValue7");

		DecimalFormat df = new DecimalFormat("0");
		String itemNo =String.valueOf(df.format((System.currentTimeMillis() + Math.floor((Math.random() * 10000)))));
		
		if(itemDescribe1!=null &&!itemDescribe1.equals("") && itemValue1!=null && !itemValue1.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe1);
			modelInfo.setItemValue(Double.valueOf(itemValue1));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe2!=null &&!itemDescribe2.equals("") && itemValue2!=null && !itemValue2.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe2);
			modelInfo.setItemValue(Double.valueOf(itemValue2));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe3!=null &&!itemDescribe3.equals("") && itemValue3!=null && !itemValue3.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe3);
			modelInfo.setItemValue(Double.valueOf(itemValue3));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		

		if(itemDescribe4!=null &&!itemDescribe4.equals("") && itemValue4!=null && !itemValue4.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe4);
			modelInfo.setItemValue(Double.valueOf(itemValue4));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe5!=null &&!itemDescribe5.equals("") && itemValue5!=null && !itemValue5.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe5);
			modelInfo.setItemValue(Double.valueOf(itemValue5));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe6!=null &&!itemDescribe6.equals("") && itemValue6!=null && !itemValue6.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe6);
			modelInfo.setItemValue(Double.valueOf(itemValue6));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		if(itemDescribe7!=null &&!itemDescribe7.equals("") && itemValue7!=null && !itemValue7.equals("")){		
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setModelId(modelId);
			modelInfo.setDataFlag(ModelInfo.ADJUST_ITEM);
			modelInfo.setDescribe1(describe1);
			modelInfo.setDescribe2(describe2);
			modelInfo.setDescribe3(describe3);
			modelInfo.setItemDescribe(itemDescribe7);
			modelInfo.setItemValue(Double.valueOf(itemValue7));
			modelInfo.setItemNo(itemNo);
			list.add(modelInfo);
		}
		
		//批量插入
		modelService.insertModelInfo(list);
		
		response.getWriter().print("{success:true}");
		
	}
	

	//修改定性因素
	@RequestMapping("/editAdjustment")
	public void editAdjustment(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String serialNo = request.getParameter("serialNo");
		String field = request.getParameter("field");
		String originalValue = request.getParameter("originalValue");
		String modifiedValue = request.getParameter("modifiedValue");
		String describe2 = request.getParameter("describe2");
		String modelId = request.getSession().getAttribute("modelId").toString();
		
		List<ModelInfo> itemList = new ArrayList<ModelInfo>();
		String dataFlag = request.getParameter("dataFlag");
		
		if(field.equals("describe2")) describe2 = originalValue;
		itemList =modelService.findModelInfoByModelIdAndDescribe2AndDataFlagAndModifiedField(modelId,describe2,dataFlag,field,originalValue); 
		
		for (ModelInfo mi: itemList){
			if(field.equals("describe1")){
				mi.setDescribe1(modifiedValue);
			}
			else if (field.equals("describe2")){
				mi.setDescribe2(modifiedValue);
			}
			else if (field.equals("describe3")){
				mi.setDescribe3(modifiedValue);
			}
			else if (field.equals("itemDescribe")){
				mi.setItemDescribe(modifiedValue);
			}
			else if (field.equals("itemValue")){
				mi.setItemValue(Double.valueOf(modifiedValue));	
			}
			else if (field.equals("itemWeight")){
				mi.setItemWeight(Double.valueOf(modifiedValue));
			}
			modelService.updateModelInfo(mi);
		}
		
		response.getWriter().print("{success:true}");
		
	}
	
	
	//model_level
	@RequestMapping("/listModelLevel")
	public void listModelLevel(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		List<ModelLevel> modelLevelList = new ArrayList<ModelLevel>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		 
		modelLevelList = modelService.findModelLevelByModelId(modelId); 
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		JSONArray JA=JSONArray.fromObject(modelLevelList);
		out.print(JA);
	}

	//添加ModelLevel
	@RequestMapping("/addModelLevel")
	public void addModelLevel(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		List<ModelLevel> list = new ArrayList<ModelLevel>();
		String modelId = request.getSession().getAttribute("modelId").toString();
		String newModelLevelRecord = request.getParameter("newRecord");
		//newModelLevelRecord = newModelLevelRecord.replaceAll("{serialNo:\"\",pdlevel:\"\",modelScore:}", "");
		//newModelLevelRecord = newModelLevelRecord.replaceAll(",,", ",");
		
		JSONArray ja = JSONArray.fromObject(newModelLevelRecord);   
		
		for (int i = 0; i < ja.size(); i++) {
			
			JSONObject jo = (JSONObject)ja.get(i);
			
			String serialNo = jo.get("serialNo").toString();
			String pdlevel = jo.get("pdlevel").toString();
			String modelScore = jo.get("modelScore").toString();
			
			ModelLevel modelLevel= new ModelLevel();
			if(!serialNo.equals("")) modelLevel.setSerialNo(serialNo);
			modelLevel.setPdlevel(pdlevel);
			modelLevel.setModelScore(Double.valueOf(modelScore));
			modelLevel.setModelId(modelId);
			
			list.add(modelLevel);
		
		}
		
		//批量插入
		modelService.insertModelLevel(list);
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		//JSONArray JA=JSONArray.fromObject(modelLevelList);
		out.print("{success:true}");
	}
	

	
/**
 * 主标尺管理
 */
	//列出所有的主标尺版本信息，按照状态和时间排序
	@RequestMapping("/listSortedMainScale")
	public void listSortedMainScale(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		List<MainscaleHis> mainScaleList = new ArrayList<MainscaleHis>();
		
		// 对模型历史进行排序
		
		List<MainscaleHis> notReleasedMainScaleList = modelService.findNotReleasedMainScale();
		List<MainscaleHis> nonNotReleasedMainScaleList = modelService.findNonNotReleasedMainScale();
		
		mainScaleList.addAll(notReleasedMainScaleList);
		mainScaleList.addAll(nonNotReleasedMainScaleList);
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		
		List<MainscaleHis> pageList;
		if(mainScaleList.size()>start+limit)
			pageList = mainScaleList.subList(start, limit+start); 
		else
			pageList = mainScaleList.subList(start,mainScaleList.size());
		
		for(MainscaleHis mainscale : pageList){
			mainscale.setMainScaleState(DataDictionary.getInstance().getNameByCodeAndId("ModelState", mainscale.getMainScaleState()));
		}
		
		Map<String, Object> myMap = new HashMap<String, Object>(3);
		myMap.put("total", mainScaleList.size());
		myMap.put("resultData", pageList);
		JSONObject JO=JSONObject.fromObject(myMap);
		out.print(JO);
		
		log.info("JSON数据："+JO);
		
	}
	
	//版本生效
	@RequestMapping("/effectMainScale")
	public void effectMainScale(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String mainScaleId = request.getParameter("mainScaleId");
		String updateLog = request.getParameter("updateLog");
		MainscaleHis mainscale = new MainscaleHis();
		
		if(mainScaleId!=null && !mainScaleId.equals("")){
			
			mainscale = modelService.findMainscaleHisById(mainScaleId);
			
			//置其他已生效Model为失效状态
			MainscaleHis effectedMainScale = new MainscaleHis();
			effectedMainScale = modelService.findMainscaleByState(MainscaleHis.EFFECTED);
			if (effectedMainScale != null){
				effectedMainScale.setMainScaleState(MainscaleHis.NOT_EFFECTED);
				effectedMainScale.setEndDate(CalendarUtil.getCurrentDateStr());
				effectedMainScale.setUpdateDate(CalendarUtil.getCurrentDateStr());
				effectedMainScale.setStartDate("");
				modelService.updateMainscaleHis(effectedMainScale);
			}
			
			//更新当前Model为生效状态
			mainscale.setMainScaleState(MainscaleHis.EFFECTED);
			mainscale.setUpdateLog(updateLog);
			mainscale.setStartDate(CalendarUtil.getCurrentDateStr());
			mainscale.setEndDate("");
			mainscale.setUpdateDate(CalendarUtil.getCurrentDateStr());
			modelService.updateMainscaleHis(mainscale);
			
			response.getWriter().print("{success:true}");

	


		}
	}
	
	@RequestMapping("/copyModel")
	public String copyModel(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		//复制当前大类子类生效版本的定量，定性，调整项信息
		//存储返回值若为0表示非从复制页面进入，1表示复制成功，2表示版本不是未发布版本，3表示当前类别无生效版本
		String returnFlag = "0";
		log.info("复制版本");
		
		ModelHis model = (ModelHis)request.getSession().getAttribute("model");
		ModelHis orginModel = modelService.findModelByKind1AndKind2AndState(model.getModelKind1(), model.getModelKind2(), ModelHis.EFFECTED);
		
		//如果找到当前类别有生效的版本，则进行复制
		//只能对未发布的版本进行复制
		if(orginModel!=null && model.getModelState().equals(ModelHis.NOT_RELEASED)){
			log.info("当前类别有生效版本");
			List<ModelInfo> orginList = modelService.findModelInfoByModelId(orginModel.getModelId());
			List<ModelInfo> list = new ArrayList<ModelInfo>();
			//如果该model中已有数据，先清空
			List<ModelInfo> nowList = modelService.findModelInfoByModelId(model.getModelId());
			if(nowList.size()>0){
				modelService.deleteModelInfo(nowList);
			}
			
			//对每条记录，为新的model创建一条新的记录
			for(ModelInfo mi : orginList){
				ModelInfo modelInfo = new ModelInfo();
				modelInfo.setModelId(model.getModelId());
				modelInfo.setDataFlag(mi.getDataFlag());
				modelInfo.setDescribe1(mi.getDescribe1());
				modelInfo.setDescribe2(mi.getDescribe2());
				modelInfo.setDescribe3(mi.getDescribe3());
				modelInfo.setItemDescribe(mi.getItemDescribe());
				modelInfo.setItemValue(mi.getItemValue());
				modelInfo.setItemWeight(mi.getItemWeight());
				modelInfo.setInputDate(CalendarUtil.getCurrentDateStr());
				modelInfo.setUpdateDate(CalendarUtil.getCurrentDateStr());
								
				list.add(modelInfo);
				returnFlag = "1";
			}
			
			//批量插入
			if(list.size()>0){
				modelService.insertModelInfo(list);
			}	
			
			StringBuffer sb = new StringBuffer();
	        sb.append("<Script language=\"javaScript\">\r\n");
	        sb.append("alert(\"");
	        sb.append( "复制成功" );
	        sb.append("\");");
	        sb.append("\r\n");
	        sb.append("</Script>\r\n");
	        try {
		        response.setContentType("text/html;charset=utf-8");
		        request.setCharacterEncoding("utf-8");
		        PrintWriter out = response.getWriter();
		        out.println( sb.toString() );
	        } catch (IOException e) {
	        	log.error(e.getMessage());
	        }
			
		}else if(orginModel!=null && !model.getModelState().equals(ModelHis.NOT_RELEASED)){
			log.info("当前类别无生效版本或本版本不是未发布状态");
			StringBuffer sb = new StringBuffer();
	        sb.append("<Script language=\"javaScript\">\r\n");
	        sb.append("alert(\"");
	        sb.append( "该类别下无最新版本" );
	        sb.append("\");");
	        sb.append("\r\n");
	        sb.append("history.back();");
	        sb.append("</Script>\r\n");
	        try {
		        response.setContentType("text/html;charset=utf-8");
		        request.setCharacterEncoding("utf-8");
		        PrintWriter out = response.getWriter();
		        out.println( sb.toString() );
	        } catch (IOException e) {
	        	log.error(e.getMessage());
	        }
	        returnFlag = "2";
		}else{
			returnFlag = "3";
		}
		
		return "redirect:viewDetail.do?modelId="+model.getModelId()+"&returnFlag="+returnFlag;
	}
	
	
	//主标尺——版本发布
	@RequestMapping("/releaseMainScale")
	public void releaseMainScale(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String mainScaleId = request.getParameter("mainScaleId");
		String updateLog = request.getParameter("updateLog");
		MainscaleHis mainscale = new MainscaleHis();
		
		if(mainScaleId!=null && !mainScaleId.equals("")){
			
			mainscale = modelService.findMainscaleHisById(mainScaleId);	
			mainscale.setUpdateLog(updateLog);
			mainscale.setMainScaleState(MainscaleHis.RELEASED);
			mainscale.setUpdateDate(CalendarUtil.getCurrentDateStr());
			modelService.updateMainscaleHis(mainscale);

		}
		response.getWriter().print("{success:true}");
	}
	
	//将发布置为未发布
	@RequestMapping("/notReleaseMainScale")
	public void notReleaseMainScale(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String mainScaleId = request.getParameter("mainScaleId");
		String updateLog = request.getParameter("updateLog");
		MainscaleHis mainscale = new MainscaleHis();
		
		if(mainScaleId!=null && !mainScaleId.equals("")){
			mainscale = modelService.findMainscaleHisById(mainScaleId);	
		
			mainscale.setUpdateLog(updateLog);
			mainscale.setMainScaleState(MainscaleHis.NOT_RELEASED);
			mainscale.setUpdateDate(CalendarUtil.getCurrentDateStr());
			
			modelService.updateMainscaleHis(mainscale);
		}
		
		response.getWriter().print("{success:true}");

	}
	
	//列出主标尺版本详情
	@RequestMapping("/listMainScaleInfo")
	public void listMainScaleInfo(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		List<MainscaleInfo> mainScaleInfoList = new ArrayList<MainscaleInfo>();
		String mainScaleId = request.getSession().getAttribute("mainScaleId").toString();
		if(mainScaleId != null && !mainScaleId.equals("") )
			mainScaleInfoList = modelService.findMainscaleInfoByMainscaleId(mainScaleId);
		

		JSONArray JA=JSONArray.fromObject(mainScaleInfoList);
		out.print(JA);
		
		//log.info("JSON数据："+JO);
		
	}
	
	//添加mainscaleinfo
	@RequestMapping("/addMainscaleInfo")
	public void addMainscaleInfo(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String mainScaleId = request.getSession().getAttribute("mainScaleId").toString();
		
		List<MainscaleInfo> list = new ArrayList<MainscaleInfo>();
		
		String newMainscaleInfoRecord = request.getParameter("newRecord");
		
		JSONArray ja = JSONArray.fromObject(newMainscaleInfoRecord);   
		
		for (int i = 0; i < ja.size(); i++) {
			
			JSONObject jo = (JSONObject)ja.get(i);
			
			System.out.println(jo.get("pdlevel"));
			System.out.println(jo.get("pdvalue").getClass());
			
			String serialNo = jo.get("serialNo").toString();
			String pdlevel = jo.get("pdlevel").toString();
			String pdvalue = jo.get("pdvalue").toString();
			
			if(serialNo.equals("")){
				
				MainscaleInfo mainscaleInfo= new MainscaleInfo();
				mainscaleInfo.setPdlevel(pdlevel);
				mainscaleInfo.setPdvalue(Double.valueOf(pdvalue));
				mainscaleInfo.setMainScaleId(mainScaleId);
				
				list.add(mainscaleInfo);
			}
			else {
				MainscaleInfo exitedMainscaleInfo = new MainscaleInfo();
				exitedMainscaleInfo = modelService.findMainscaleInfoById(serialNo);
				exitedMainscaleInfo.setPdlevel(pdlevel);
				exitedMainscaleInfo.setPdvalue(Double.valueOf(pdvalue));
				
				modelService.updateMainscaleInfo(exitedMainscaleInfo);
			}
		
		}
		
		//批量插入
		modelService.insertMainScaleInfo(list);
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		//JSONArray JA=JSONArray.fromObject(modelLevelList);
		out.print("{success:true}");
	}
	
	@RequestMapping("/viewMSDetail")
	public String viewMSDetail(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		request.getSession().removeAttribute("mainScaleId");
		request.getSession().setAttribute("mainScaleId", request.getParameter("mainScaleId"));
		request.getSession().removeAttribute("mainscale");
		request.getSession().setAttribute("mainscale", modelService.findMainscaleHisById(request.getParameter("mainScaleId")));
		//request.setAttribute("returnFlag", request.getParameter("returnFlag"));
		
		return "model/MainScaleManagement_VersionDetail";
	}
	
	//检查该版本是否存在
	@RequestMapping("/checkMainScale")
	public void checkMainScale(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String version = request.getParameter("mainScaleVersion");
		String name = request.getParameter("mainScaleName");
		
		int isExit = 0;
		
		List<MainscaleHis> list = modelService.findMainScaleByVersionAndName(version, name);
		
		if (list.size()!=0){
			isExit = 1;
			response.getWriter().print(isExit);
		}
		else{
			isExit = 0;
			response.getWriter().print(isExit);
		}
		
	}
	
	@RequestMapping("/addMainscale")
	public String addMainscale(HttpServletRequest request,
			HttpServletResponse response, MainscaleHis mainscale) throws IOException {
		
		mainscale.setUpdateDate(CalendarUtil.getCurrentDateStr());
		mainscale.setMainScaleState(MainscaleHis.NOT_RELEASED);
		
		modelService.insertMainscale(mainscale);
		
		//当前生效版本
		MainscaleHis effectedMS = new MainscaleHis();
		effectedMS = modelService.findMainscaleByState(MainscaleHis.EFFECTED);
		
		//当前生效版本详情
		List<MainscaleInfo> effectedMSInfoList = new ArrayList<MainscaleInfo>();
		if(effectedMS!=null)
			effectedMSInfoList = modelService.findMainscaleInfoByMainscaleId(effectedMS.getMainScaleId());
		
		if(effectedMSInfoList != null && effectedMSInfoList.size()>0){
			List<MainscaleInfo> copiedList = new ArrayList<MainscaleInfo>();
			
			for (MainscaleInfo ms: effectedMSInfoList){
				MainscaleInfo copiedMSInfo = new MainscaleInfo();
				copiedMSInfo.setMainScaleId(mainscale.getMainScaleId());
				copiedMSInfo.setPdlevel(ms.getPdlevel());
				copiedMSInfo.setPdvalue(ms.getPdvalue());
				copiedList.add(copiedMSInfo);
			}
			
			modelService.insertMainScaleInfo(copiedList);
		}
		
		request.getSession().removeAttribute("mainScaleId");
		request.getSession().setAttribute("mainScaleId", mainscale.getMainScaleId());
		request.getSession().removeAttribute("mainscale");
		request.getSession().setAttribute("mainscale", mainscale);
		
		return "model/MainScaleManagement_VersionDetail";
	}

	/*
	 * 参数管理
	 */
	@RequestMapping("/saveLeverParams")
	public String saveLeverParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("LeverParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("LeverParams", ParamModelInit.getInstance().getLeverParams());
		
		return "model/LeverParam";
	}
	@RequestMapping("/saveDiscountParams")
	public String saveDiscountParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("DiscountParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("DiscountParams", ParamModelInit.getInstance().getDiscountParams());
		
		return "model/DiscountParam";
	}
	
	@RequestMapping("/saveIndustryParams")
	public String saveIndustryParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("IndustryParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("IndustryParams", ParamModelInit.getInstance().getIndustryParams());
		
		return "model/IndustryParam";
	}
	
	@RequestMapping("/saveAreaParams")
	public String saveAreaParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("AreaParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("AreaParams", ParamModelInit.getInstance().getAreaParams());
		
		return "model/AreaParam";
	}
	
	@RequestMapping("/saveSolvencyParams")
	public String saveSolvencyParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("SolvencyParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("SolvencyParams", ParamModelInit.getInstance().getSolvencyParams());
		
		return "model/SolvencyParam";
	}
	
	@RequestMapping("/saveCCFParams")
	public String saveCCFParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("CCFParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("CCFParams", ParamModelInit.getInstance().getCCFParams());
		
		return "model/CCFParam";
	}
	
	@RequestMapping("/saveIndAccessLine")
	public String saveIndAccessLine(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("IndAccessLine").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("IndAccessLine", ParamModelInit.getInstance().getAccessLine());
		
		return "model/IndAccessLine";
	}

	@RequestMapping("/saveCustLimitParams")
	public String saveCustLimitParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("CustLimitParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("saveCustLimitParams", ParamModelInit.getInstance().getLimitParams());
		
		return "model/CustLimitParam";
	}
	
	@RequestMapping("/saveFTPParams")
	public String saveFTPParams(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException{
		List<CodeLib> list = new ArrayList<CodeLib>();
		Enumeration paras = request.getParameterNames();
		while(paras.hasMoreElements()){
			String paraName = (String) paras.nextElement();
			String value = request.getParameter(paraName);
			CodeLib codeLib = DataDictionary.getInstance().getDataDictionary().get("FTPParam").get(paraName);
			codeLib.setItemName(value);
			list.add(codeLib);
		}
		modelService.updateCodeLib(list);
		model.addAttribute("FTPParams", ParamModelInit.getInstance().getFTPParams());
		
		return "model/FTPParam";
	}
}
